<?php
/**
 * Copyright (C), 2021-2021, Shall Buy Life info. Co., Ltd.
 * FileName: UserService.php
 * Description: 说明
 *
 * @author old_liu_cms
 * @Create Date    2021/10/9 15:17
 * @Update Date    2021/10/9 15:17 By old_liu_cms
 * @version v1.0
 */
namespace App\Services;

use App\Constants\ErrorResponse;
use App\Constants\AuthConstant;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class UserService implements AuthConstant
{
    private $userId;
    public function __construct()
    {
        $this->userId = auth('users')->id();
    }

    /**
     * FunctionName：login
     * Description：
     * Author：old_lwl_cms
     * @param array $params
     * @return array
     */
    public function login(array $params): array
    {
        // TODO: Implement login() method.
        if (!$token = auth('users')->attempt($params)) {
            errorHttpResponse(ErrorResponse::ERROR_USERNAME_PASSWORD);
        }
        return  $this->respondWithToken($token);
    }

    /**
     * FunctionName：info
     * Description：
     * Author：old_lwl_cms
     * @return object
     */
    public function info(): object
    {
        // TODO: Implement info() method.
        return auth('users')->user();
    }

    /**
     * FunctionName：logout
     * Description：
     * Author：old_lwl_cms
     * @return array|void
     */
    public function logout()
    {
        // TODO: Implement logout() method.
        return auth('users')->logout();
    }

    /**
     * FunctionName：updateInfo
     * Description：
     * Author：old_lwl_cms
     * @param array $params
     * @return array
     */
    public function updateInfo(array $params)
    {
        // TODO: Implement updateInfo() method.
        if (!User::edit($this->userId,$params)) {
            errorHttpResponse(ErrorResponse::ERROR_OPERATION_FAIL);
        }
        return null;
    }

    /**
     * FunctionName：updatePassword
     * Description：
     * Author：old_lwl_cms
     * @param string $password
     * @return array
     */
    public function updatePassword(string $password)
    {
        // TODO: Implement updatePassword() method.
        $password = Hash::make($password);
        $params = compact('password');
        if (!User::edit($this->userId,$params)) {
            errorHttpResponse(ErrorResponse::ERROR_OPERATION_FAIL);
        }
        return null;
    }

    /**
     * FunctionName：respondWithToken
     * Description：对应令牌
     * Author：old_liu_cms
     * @param string $token
     * @return array
     */
    private function respondWithToken(string $token): array
    {
        return [
            'token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('users')->factory()->getTTL()
        ];
    }
}
